#include "lm2904_driver.h"
#include <string.h>
#define HDF_LOGE(fmt, ...) printf("[ERROR] " fmt "\n", ##__VA_ARGS__)
static struct {
    float buffer[FILTER_WINDOW_SIZE];
    unsigned int index;
    uint8_t initialized;
} g_filterCtx = { .index = 0, .initialized = 0 };

// ADC值转电压（RK2206为10位ADC）
static float ConvertAdcToVoltage(uint32_t rawValue) {
    const float maxAdcValue = 1023.0f; 
    const float refVoltage = 3.3f;     // 根据硬件确认
    return (rawValue / maxAdcValue) * refVoltage;
}

// 噪声电压转分贝计算
static float VoltageToDecibel(float voltage) {
    static float vp = 0.0f;
    
    // 根据VCC初始化峰值电压
    if (vp <= 0.01f) {
        if (MODULE_VCC >= 7.0f)      vp = 5.0f;
        else if (MODULE_VCC >= 5.0f) vp = 2.8f;
        else                         vp = MODULE_VCC * 0.56f;
    }

    // 限幅处理
    if (voltage < SILENT_VOLTAGE) voltage = SILENT_VOLTAGE;
    if (voltage > vp) voltage = vp;
    
    // 线性转换
    return DB_BASE + (voltage - SILENT_VOLTAGE) * 
           (DB_MAX - DB_BASE) / (vp - SILENT_VOLTAGE);
}

// 滑动滤波算法
static float ApplyMovingAverage(float newValue) {
    g_filterCtx.buffer[g_filterCtx.index] = newValue;
    g_filterCtx.index = (g_filterCtx.index + 1) % FILTER_WINDOW_SIZE;

    float sum = 0.0f;
    for(int i=0; i<FILTER_WINDOW_SIZE; i++) {
        sum += g_filterCtx.buffer[i];
    }
    return sum / FILTER_WINDOW_SIZE;
}
int LM2904Init(void) {
    if (g_filterCtx.initialized) return IOT_SUCCESS;

    uint32_t ret = IoTAdcInit(ADC_CHANNEL_ID); // 关键改动：使用HAL接口
    if (ret != IOT_SUCCESS) {
        HDF_LOGE("ADC init failed:0x%X", ret);
        return ret;
    }

    memset(g_filterCtx.buffer, 0, sizeof(g_filterCtx.buffer));
    g_filterCtx.initialized = 1;
    return IOT_SUCCESS;
}

float GetFilteredNoiseLevel(void) {
    if (!g_filterCtx.initialized) return NAN;

    uint32_t rawValue = 0;
    uint32_t ret = IoTAdcGetVal(ADC_CHANNEL_ID, &rawValue); // 关键改动：直接取值
    if (ret != IOT_SUCCESS) {
        HDF_LOGE("ADC read err:0x%X", ret);
        return NAN;
    }

    float voltage = ConvertAdcToVoltage(rawValue);
    float decibel = VoltageToDecibel(voltage);
    return ApplyMovingAverage(decibel);
}